
var express = require('express');

const UserModel = require('../modules/user');
const md5=require('md5')
var router = express.Router();


/* GET home page. */
router.get('/reg', (req, res)=>{
    res.render('registe')
});
router.post('/reg', (req, res)=>{
    const data={...req.body,password:md5(req.body.password)}
    UserModel.create(data).then(response=>{
      res.send('注册成功！')
    }).catch(error=>{
        res.send('注册失败！')
        console.log(error.message)
    })
});
router.get('/login', (req, res)=>{
    res.render('login')
});
router.get('/logout', (req, res)=>{
    res.clearCookie('name');
    res.render('success',{msg:'退出成功',url:'###'})
});
router.post('/login', (req, res)=>{
    const {username,password}=req.body
    UserModel.find({$and:[{username:username},{password:md5(password)}]}).then(response=>{
       if(response.length!==0){
        res.cookie('name','wby',{maxAge:1000*60*60*24*30})
        res.render('success',{url:'/account',msg:'登录成功'})
       }else{
       return res.send('账号或密码错误！')
       }
    }).catch(error=>{
        console.log(error.message)
    })
});


module.exports = router;
